package com.dqhl.business.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.modle.Coupon;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.AddPromotionCouponPopupWindow;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: 整单促销添加商品
 * autour: guanluocang
 * date: 2016/11/9 15:34
 */
public class AddPromotionAllActivity extends BaseActivity implements View.OnClickListener, OnDateSetListener {

    private ImageView iv_goodsGoBack;
    private TextView tv_goodsTopTitle;
    private TextView tv_onlyType;
    private TextView tv_moreGoods;
    private TextView tv_startTime;
    private TextView tv_endTime;
    private EditText et_name;
    private TextView tv_selectCount;
    private AddPromotionCouponPopupWindow addPromotionCouponPopupWindow;

    //时间选择器
    TimePickerDialog mDialogMonthDayHourMinute;
    TimePickerDialog mDialogAll;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    private String timeFlag = "1";
    private TextView tv_allSave;
    private TextView tv_saveAndRelase;
    private String coupon_id = "";
    private static final int RESULTCODE = 101;
    private final int REQUEST_CODE = 1;
    private final int REQUEST_CODE_TWO = 2;
    private final int RESULTCODE_TWO = 123;
    private List<Coupon> couponList;
    private String class_id = "";
    private List<String> goodsIdList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_promotion_all);
        initView();
        TimePicker();
    }

    private void initView() {
        iv_goodsGoBack = (ImageView) findViewById(R.id.iv_goodsGoBack);
        tv_goodsTopTitle = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("整单促销");
        tv_onlyType = (TextView) findViewById(R.id.tv_onlyType);
        tv_moreGoods = (TextView) findViewById(R.id.tv_moreGoods);
        tv_startTime = (TextView) findViewById(R.id.tv_startTime);
        tv_endTime = (TextView) findViewById(R.id.tv_endTime);
        et_name = (EditText) findViewById(R.id.et_name);
        tv_selectCount = (TextView) findViewById(R.id.tv_selectCount);
        tv_allSave = (TextView) findViewById(R.id.tv_allSave);
        tv_saveAndRelase = (TextView) findViewById(R.id.tv_saveAndRelase);

        tv_saveAndRelase.setOnClickListener(this);
        tv_allSave.setOnClickListener(this);
        tv_selectCount.setOnClickListener(this);
        tv_endTime.setOnClickListener(this);
        tv_startTime.setOnClickListener(this);
        tv_onlyType.setOnClickListener(this);
        tv_moreGoods.setOnClickListener(this);
        iv_goodsGoBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //选择优惠券
            case R.id.tv_selectCount:
                SelectCoupon();
                break;
            //截止时间
            case R.id.tv_endTime:
                timeFlag = "2";
                mDialogMonthDayHourMinute.show(getSupportFragmentManager(), "year_month_day");
                break;
            //起始时间
            case R.id.tv_startTime:
                timeFlag = "1";
                mDialogMonthDayHourMinute.show(getSupportFragmentManager(), "year_month_day");
                break;
            //指定类型
            case R.id.tv_onlyType:
                overlay(PromotionTypeDialogActivity.class, REQUEST_CODE_TWO);
                tv_onlyType.setTextColor(ContextCompat.getColor(this, R.color.daiqianshou));
                tv_moreGoods.setTextColor(ContextCompat.getColor(this, R.color.main_textContent));
                break;
            //指定多个商品
            case R.id.tv_moreGoods:
                class_id = "";
                tv_onlyType.setTextColor(ContextCompat.getColor(this, R.color.main_textContent));
                tv_moreGoods.setTextColor(ContextCompat.getColor(this, R.color.daiqianshou));
                overlay(PromotionMoreDialogActivity.class, REQUEST_CODE);
                break;
            case R.id.iv_goodsGoBack:
                finish();
                break;
            //保存
            case R.id.tv_allSave:
                doSubmit("1");
                break;
            //保存发布
            case R.id.tv_saveAndRelase:
                doSubmit("2");
                break;

        }
    }

    // 1  保存到未发布  2  到已发布
    private void doSubmit(String status) {

        String name = et_name.getText().toString().trim();
        String startTime = tv_startTime.getText().toString().trim();
        String endTime = tv_endTime.getText().toString().trim();
        if ("".equals(name)) {
            toast("名称不能为空");
        } else if ("".equals(startTime)) {
            toast("起始时间不能为空");
        } else if ("".equals(endTime)) {
            toast("截止不能为空");
        } else if ("".equals(coupon_id)) {
            toast("优惠券不能为空");
        } else {
            showCustomLoadBar(".");
            RequestParams params = new RequestParams(Config.discount_Alladd);
            params.addBodyParameter("seller_id", user.getUser_id());
            params.addBodyParameter("name", name);
            params.addBodyParameter("start_time", startTime);
            params.addBodyParameter("end_time", endTime);
            Dlog.e(goodsIdList.size() + " GG数组  " + goodsIdList + " class_id " + class_id);
            //class_id为空 传多个商品
            if ("".equals(class_id) && goodsIdList.size() <= 0){
                toast("商品ID 不能为空");
            }else if("".equals(class_id) && goodsIdList.size() > 0){
                Dlog.e("GG GoodsListGoodsListGoodsListGoodsList");
                params.addBodyParameter("goods", goodsIdList + "");
            }else if(!"".equals(class_id) && goodsIdList.size() <= 0){
                Dlog.e("GG class_idclass_idclass_idclass_idclass_id");
                params.addBodyParameter("class", class_id);
            }
//
//
//                if (goodsIdList.size() > 0) {
//                    params.addBodyParameter("goods", goodsIdList + "");
//                } else if (!"".equals(class_id)) {
//                    params.addBodyParameter("class", class_id);
//                } else {
//                    toast("商品ID 不能为空");
//                }
            params.addBodyParameter("coupon_id", coupon_id);
            params.addBodyParameter("state", status);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("GG添加整单促销" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getErrMsg(result);
                    if (errCode == 0) {
                        forward(PromotionAllRecordActivity.class);
                        toast(errMsg);
                    } else {
                        toast(errMsg);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }

    }

    //优惠券接口
    public void SelectCoupon() {

        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.personal_coupon_list);
        params.addBodyParameter("seller_id", user.getUser_id());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    couponList = JSON.parseArray(data, Coupon.class);
                    addPromotionCouponPopupWindow = new AddPromotionCouponPopupWindow(AddPromotionAllActivity.this, couponList,
                            new AddPromotionCouponPopupWindow.IOnItemSelectListener() {
                                @Override
                                public void onItemClick(int position) {
                                    tv_selectCount.setText(couponList.get(position).getDenomination());
                                    coupon_id = couponList.get(position).getId();
                                }
                            });
                    addPromotionCouponPopupWindow.setWidth(tv_selectCount.getWidth());
                    addPromotionCouponPopupWindow.showAsDropDown(tv_selectCount);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });

    }

    @Override
    public void onDateSet(com.jzxiang.pickerview.TimePickerDialog timePickerView, long millseconds) {
        String text = getDateToString(millseconds);
        long nowTime = System.currentTimeMillis();
        if(nowTime<millseconds){
            if ("1".equals(timeFlag)) {
                tv_startTime.setText(text);
            } else {
                tv_endTime.setText(text);
            }
        }else{
            toast("请大于当前日期");
        }
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    //时间选择器
    public void TimePicker() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAll = new com.jzxiang.pickerview.TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("Cancel")
                .setSureStringId("Sure")
                .setTitleStringId("TimePicker")
                .setYearText("Year")
                .setMonthText("Month")
                .setDayText("Day")
                .setHourText("Hour")
                .setMinuteText("Minute")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();


        mDialogMonthDayHourMinute = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(this)
                .build();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULTCODE) {
            goodsIdList = data.getStringArrayListExtra("goodsList");
            Dlog.e("goodsIdList" + goodsIdList);
        }
        if (requestCode == REQUEST_CODE_TWO && resultCode == RESULTCODE_TWO) {

            class_id = data.getStringExtra("class_id");
            Dlog.e("class_id" + class_id);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
